package com.edu.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edu.pojo.*;
import com.edu.service.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(value="/chair")
public class ChairContraller {
	
	@Autowired
	private MemberService memberService;
	@Autowired
	private userservice userservice1;
	
	@Autowired
	private DepartmentService departmentService;

	
	@Autowired
	private CollegeService collegeService;
	
	@Autowired
	private AnnouncementService announcementService;

	@Autowired
	private  ActivitieService activitieService;

	@Autowired
	private  MissionService missionService;
	@Autowired
	private  MoneyService moneyService;
	@Autowired
	private  FileService fileService;
	
	
	@RequestMapping(value="/main",method=RequestMethod.GET)
	public String ToMainForm() {
		return "Chair/main";
	}
	
	@RequestMapping(value="/modifyPassword",method=RequestMethod.GET)
	public String ToModifyPassword() {
		return "Chair/ChairModifyPassword";
	}
	
	@RequestMapping(value="/ministerAdd",method=RequestMethod.GET)
	public String ToMinisterAdd() {
		return "Chair/MinisterAdd";
	}
	
	@RequestMapping(value="/ministerManage",method=RequestMethod.GET)
	public String ToMinisterManage() {
		
		return "Chair/MinisterManage";
	}
	
	@RequestMapping(value="/memberAdd",method=RequestMethod.GET)
	public String ToMemberAdd() {
		return "Chair/MemberAdd";
	}
	
	@RequestMapping(value="/memberManage",method=RequestMethod.GET)
	public String TomemberManage() {
		return "Chair/MemberManage";
	}
	

	
	@RequestMapping(value="/checkMission",method=RequestMethod.GET)
	public String CheckMission(Model model) {

//		List<Mission> list = missionService.showAllMission("chair");

		List<Mission> list = missionService.showNeedMission(2,"chair");

		for(int i=0;i<list.size();i++) {
			int status = list.get(i).getStatus();
			 if(status == 2) {
				list.get(i).setStatusName("审核中");
			}
		}
//		for(int i=0;i<list.size();i++) {
//			int status = Integer.parseInt(list.get(i).getStatus());
//			if(status == 1) {
//				list.get(i).setStatusName("未完成");
//			}else if(status == 2) {
//				list.get(i).setStatusName("审核中");
//			}else if(status == 3){
//				list.get(i).setStatusName("已完成");
//			}
//		}
		model.addAttribute("missionList",list);

		return "Chair/MissionManage";
	}

	@RequestMapping(value="/checkFinishMission",method=RequestMethod.GET)
	public String checkFinishMission(Model model) {

		List<Mission> list = missionService.showNeedMission(3,"chair");

		for(int i=0;i<list.size();i++) {
			int status = list.get(i).getStatus();
			if(status == 3) {
				list.get(i).setStatusName("已完成");
			}
		}
		model.addAttribute("missionList",list);

		return "Chair/MissionManage";
	}
	@RequestMapping(value="/checkIncompleteMission",method=RequestMethod.GET)
	public String CheckIncompleteMission(Model model) {
		List<Mission> list = missionService.showNeedMission(1,"chair");

		for(int i=0;i<list.size();i++) {
			int status = list.get(i).getStatus();
			if(status == 1) {
				list.get(i).setStatusName("未完成");
			}
			list.get(i).setDepartmentNa(departmentService.getNameByID(Integer.parseInt(list.get(i).getMemberNo())));
		}


		model.addAttribute("missionList",list);

		return "Chair/IncompleteMission";
	}



	@RequestMapping(value="/addmission",method=RequestMethod.GET)
	public String ToAddMission(Model model) {
//		List<Member> list = memberService.showAllMinister();
//		model.addAttribute("department",list);
		return "Chair/AddMission";
	}
	@RequestMapping(value="/approved",method=RequestMethod.GET)
	public String ToApprovedMission(Model model,int id) {
		 missionService.approved(id);

		return "redirect:/chair/checkMission";
	}
	@RequestMapping(value="/notApproved",method=RequestMethod.GET)
	public String ToNotApprovedMission(Model model,int id) {
		missionService.notApproved(id);

		return "redirect:/chair/checkMission";
	}



	@RequestMapping(value="/MinisterAdd",method=RequestMethod.POST)
	public String addMember(HttpServletRequest request, MultipartFile file,String missionName, String context,String department,Model model) throws Exception {
		Mission mission =new Mission();
		mission.setMissionName(missionName);
		mission.setContext(context);

		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date ss =new Date();
		String time4 =time.format(ss.getTime());
		Date formatTime = time.parse(time4);

		mission.setInputTime(formatTime);

		mission.setStatus(1);
		mission.setPublishman("chair");
		mission.setMemberNo(department);


		String localPath = "E:\\Java EE tomcat\\apache-tomcat-9.0.31\\webapps\\filepath\\missionPath\\";
		String exName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String fileName = UUID.randomUUID().toString()+exName;
		FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(new File(localPath+fileName)));

		mission.setMissionPath(localPath+fileName);

		missionService.addMission(mission);
		return "redirect:/chair/checkIncompleteMission";
	}

	@RequestMapping(value="/showannouncement")
	public String Announcement(Model model) {
		List<Announcement> list = announcementService.queryAnnouncement();
		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(int i=0;i<list.size();i++) {
			Date time4db = list.get(i).getInputTime();
			String formatTime = time.format(time4db);
			list.get(i).setFormatTime(formatTime);
		}
		model.addAttribute("announcementList", list);
		return "Chair/Announcement";
	}
//
	@RequestMapping(value="/PublishFile",method=RequestMethod.GET)
	public String PublishFile() {
		return "Chair/PublishFile";
	}

	@RequestMapping(value="/publishAnnouncement",method=RequestMethod.GET)
	public String PublishAnnouncement() {
		return "Chair/PublishAnnouncement";
	}

	@RequestMapping(value="/ministeradd",method=RequestMethod.POST)
	public String addMinister(HttpServletRequest request, String memberNo, String studentName,String sex,int collegeId,String phone,int department, Model model) throws Exception {
//			System.out.println(memberService.getMemberByNO(memberNo));
		if(memberService.getMemberByNO(memberNo) != null){
			model.addAttribute("message","此学号已存在");
			return "Chair/MinisterAdd";
		}
		users user = (users)request.getSession().getAttribute("user");
		String inputMan = user.getUserid();
		phone = new String(phone.getBytes("iso-8859-1"),"utf-8");

			Member member = new Member();
			member.setMemberNo(memberNo);
			member.setStudentName(studentName);
			member.setSex(sex);
			member.setCollegeId(collegeId);
			member.setPhone(phone);
			member.setDepartment(department);
			member.setInputMan(inputMan);
//			member.setInputTime(inputTime);
			member.setPermssion(2);

			users adduser =new users();
			adduser.setUserid(memberNo);
			adduser.setAccounts(memberNo);
			adduser.setPassword("123456");
			adduser.setPermission('2');

			userservice1.adduser(adduser);
			 memberService.addMember(member);
			model.addAttribute("message", "成功添加一条信息");
		   return "Chair/MinisterAdd";
	}

	@RequestMapping(value="/showAllMinister")
	public String ShowAllMinister(Model model,HttpServletResponse response) throws Exception {
		List<Member> members = memberService.showAllMinister();
		for(int i=0;i<members.size();i++) {
			System.out.println(members.get(i));
			int depmentId = members.get(i).getDepartment();
			String departmentName = departmentService.getNameByID(depmentId);
			String collegeId = members.get(i).getCollegeId()+"";
			String collegeNa = collegeService.getNameByID(collegeId);
			members.get(i).setCollegeNa(collegeNa);
			members.get(i).setDepartmentNa(departmentName);
		}
		model.addAttribute("MinisterList", members);
//		System.out.println("全部部长集合："+members);
		return "Chair/MinisterManage";
	}

	@RequestMapping(value="/deleteMinister")
	public String adminDeleteTeacher(String id,Model model) {
		 memberService.deleteStudent(id);
		 userservice1.deleteusersById(id);
		model.addAttribute("message", "成功删除一条信息");
		return "redirect:/chair/showAllMinister";
	}

	@RequestMapping(value="/modifyMinister")
	public String adminModifyTeacher(String id,Model model) {
		Member member = memberService.getMemberByNO(id);

		String memberNo = member.getMemberNo();
		String studentName = member.getStudentName();
		int depId = member.getDepartment();
		String departmentName = departmentService.getNameByID(depId);
		String sex = member.getSex();
		int collegeId =member.getCollegeId();
		String phone = member.getPhone();
		int permssion = member.getPermssion();

		model.addAttribute("memberNo", memberNo);
		model.addAttribute("studentName", studentName);
		model.addAttribute("departmentName", departmentName);
		model.addAttribute("sex", sex);
		model.addAttribute("phone", phone);
		model.addAttribute("collegeId", collegeId);
		model.addAttribute("permssion", permssion);
		return "Chair/MinisterModify";
	}

	@RequestMapping(value="/modifyMinisterToDb")
	public String modifyMinisterToDb(Model model,HttpServletRequest request, String memberNo, String studentName,String sex,String phone,String depart,String collegeId) throws Exception {
		Member member = new Member();
		member.setMemberNo(memberNo);
		member.setStudentName(studentName);
		member.setSex(sex);
		member.setCollegeId(Integer.parseInt(collegeId));
		member.setPhone(phone);
		member.setDepartment(Integer.parseInt(depart));
		member.setPermssion(2);

		int num = memberService.updateStudent(member);
//		System.out.println("修改数目："+num);
		return "redirect:/chair/showAllMinister";
	}



	@RequestMapping(value="/AddMember",method=RequestMethod.POST)
	public String addMember(HttpServletRequest request,String memberNo, String studentName,String sex,int collegeId,String phone,Integer department, Model model) throws Exception {
		if(memberService.getMemberByNO(memberNo) != null){
			model.addAttribute("message","此学号已存在");
			return "Chair/MinisterAdd";
		}
		users user = (users)request.getSession().getAttribute("user");
		String inputMan = user.getUserid();
		Member member = new Member();
		member.setMemberNo(memberNo);
		member.setStudentName(studentName);
		member.setSex(sex);
		member.setCollegeId(collegeId);
		member.setPhone(phone);
		member.setDepartment(department);
		member.setInputMan(inputMan);
//			member.setInputTime(inputTime);
		member.setPermssion(1);

		users adduser =new users();
		adduser.setUserid(memberNo);
		adduser.setAccounts(memberNo);
		adduser.setPassword("123456");
		adduser.setPermission('1');

		userservice1.adduser(adduser);
		memberService.addMember(member);
		model.addAttribute("message", "成功添加一条信息");
		return "/Chair/MemberAdd";
	}

	@RequestMapping(value="/showAllMember")
	public String ShowAllMember(Model model,HttpServletResponse response) throws Exception {
		List<Member> members = memberService.showAllMember();
		for(int i=0;i<members.size();i++) {
			System.out.println(members.get(i));
			int depmentId = members.get(i).getDepartment();
			String departmentName = departmentService.getNameByID(depmentId);
			String collegeId = members.get(i).getCollegeId()+"";
			String collegeNa = collegeService.getNameByID(collegeId);
			members.get(i).setCollegeNa(collegeNa);
			members.get(i).setDepartmentNa(departmentName);
		}
		model.addAttribute("memberList", members);
		System.out.println("全部成员集合："+members);
		return "Chair/MemberManage";
	}

	@RequestMapping(value="/modifyMember")
	public String adminModifyMember(String id,Model model) {
		Member member = memberService.getMemberByNO(id);

		String memberNo = member.getMemberNo();
		String studentName = member.getStudentName();
		int depId = member.getDepartment();
		String departmentName = departmentService.getNameByID(depId);
		String sex = member.getSex();
		int collegeId =member.getCollegeId();
		String phone = member.getPhone();
		int permssion = member.getPermssion();

		model.addAttribute("memberNo", memberNo);
		model.addAttribute("studentName", studentName);
		model.addAttribute("departmentName", departmentName);
		model.addAttribute("sex", sex);
		model.addAttribute("phone", phone);
		model.addAttribute("collegeId", collegeId);
		model.addAttribute("permssion", permssion);
		return "Chair/MemberModify";
	}

	@RequestMapping(value="/modifyMemberToDb")
	public String ModifyMemberToDb(Model model,HttpServletRequest request, String memberNo, String studentName,String sex,String phone,String depart,String collegeId) throws Exception {
		Member member = new Member();
		member.setMemberNo(memberNo);
		member.setStudentName(studentName);
		member.setSex(sex);
		member.setCollegeId(Integer.parseInt(collegeId));
		member.setPhone(phone);
		member.setDepartment(Integer.parseInt(depart));
		member.setPermssion(1);

		int num = memberService.updateStudent(member);
//		System.out.println("修改数目："+num);
		return "redirect:/chair/showAllMember";
	}

	@RequestMapping(value="/deleteMember")
	public String adminDeleteStudent(String id,Model model) {
		 memberService.deleteStudent(id);
		 userservice1.deleteusersById(id);
		model.addAttribute("message", "成功删除一条信息");
		return "redirect:/chair/showAllMember";
	}

	@RequestMapping(value="/agreeThesis")
	public String agreeThesis(int id,Model model) {

		int num = missionService.agreeThesisTitle(id);
//		System.out.println("已审核");

		return "redirect:/chair/checkMission";
	}

	@RequestMapping(value="/disagreeThesis")
	public String disgreeThesis(int id,Model model) {

		int num = missionService.disagreeThesisTitle(id);
//		System.out.println("审核不通过");

		return "redirect:/chair/checkMission";
	}

	@RequestMapping(value="/Announcementpublish")
	public String Announcementpublish(HttpServletRequest request,Model model,String context) throws Exception {
			Announcement an = new Announcement();
			an.setContext(context);

//		    System.out.println(an);
			an.setInputMan("Chair");
//		    System.out.println(an);

			Date time = new Date();
			an.setInputTime(time);
//		    System.out.println(an);

			int num = announcementService.addAnnouncement(an);
			return "redirect:/chair/showannouncement";


	}

	@RequestMapping(value="/deleteAnnouncement")
	public String adminDeleteAnnouncement(Model model,int id) throws Exception {
		int num = announcementService.deleteAnnouncementById(id);
		System.out.println("删除公告"+num+"条");
		model.addAttribute("message", "删除一个条公告");
		return "Chair/Announcement";
	}

	@RequestMapping(value="/checkApplication")
	public String checkapplication(Model model) {
		List<Money> list =moneyService.showAllOperation();

		for(int i=0;i<list.size();i++) {
			int status = list.get(i).getStatus();
			if(status == 1) {
				list.get(i).setStatusName("未接受");
			}else if(status == 2){
				list.get(i).setStatusName("通过");
			}else if(status == 3){
				list.get(i).setStatusName("未通过");
			}
			list.get(i).setMemberName(memberService.getMemberByNO(list.get(i).getMemberNo()).getStudentName());

		}
		model.addAttribute("applicationList", list);
		return "Chair/AllApplication";
	}

	@RequestMapping(value="/argeeApp")
	public String argeeApp(Model model,int id) {

		moneyService.argeeApp(id);
		return "redirect:/chair/checkApplication";
	}
	@RequestMapping(value="/disargeeApp")
	public String disargeeApp(Model model,int id) {
		moneyService.disargeeApp(id);
		return "redirect:/chair/checkApplication";
	}

		@RequestMapping(value="/upload")
	public String upload(HttpServletRequest request, MultipartFile file, String fileNa,Model model,Integer state) throws Exception {

			String localPath = "E:\\Java EE tomcat\\apache-tomcat-9.0.31\\webapps\\filepath\\";
			String exName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String fileName = UUID.randomUUID().toString()+exName;
			FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(new File(localPath+fileName)));

			com.edu.pojo.File DBfile = new com.edu.pojo.File();
			DBfile.setFileNa(fileNa+exName);
			DBfile.setFilePath(localPath+fileName);
			SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date ss =new Date();
			String time4 =time.format(ss.getTime());
			Date formatTime = time.parse(time4);

			DBfile.setInputTime(formatTime);
			DBfile.setState(state);

			fileService.addFile(DBfile);

			return "/Chair/main";


	}
	@RequestMapping(value="/showFile")
	public String showFile(Model model) {
		List<com.edu.pojo.File> list = fileService.showAllFile();
		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(int i=0;i<list.size();i++) {
			Date time4db = list.get(i).getInputTime();
			String formatTime = time.format(time4db);
			list.get(i).setFormatTime(formatTime);
		}
		model.addAttribute("FileList", list);
		return "Chair/File";
	}
	@RequestMapping(value="/fileDownload")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam("filePath") String filePath, @RequestParam("fileName") String fileName, Model model) throws Exception {
		File file = new File(filePath);
		String exname=filePath.substring(filePath.lastIndexOf("."));
		HttpHeaders headers = new HttpHeaders();
		String downloadFile = new String(fileName.getBytes("utf-8"), "iso-8859-1");
		headers.setContentDispositionFormData("attachment", downloadFile+exname);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
	}

	@RequestMapping(value="/showMemberOne",method=RequestMethod.POST)
	public String chairShowMemberOne(Model model,HttpServletResponse response, @RequestParam(value="memberNo",required=false) String memberNo) throws Exception {

		if( ("".equals(memberNo) || memberNo == null)  ) {
			ShowAllMinister(model, response);
		}else  {
			Member member = memberService.getMemberByNO(memberNo);
			if(member== null  || member.getPermssion() == 1) {
				model.addAttribute("showMessage", "没有与查询相匹配的信息");

			}
			else{

				int depId =member.getDepartment();
				String departmentName =departmentService.getNameByID(depId);
				member.setDepartmentNa(departmentName);
				model.addAttribute("member", member);
			}

		}
		return "Chair/MinisterManageShowOne";

	}
	@RequestMapping(value="/showMemberTwo",method=RequestMethod.POST)
	public String chairshowMemberTwo(Model model,HttpServletResponse response, @RequestParam(value="memberNo",required=false) String memberNo) throws Exception {

		if( ("".equals(memberNo) || memberNo == null)  ) {
			ShowAllMember(model, response);
		}else  {
			Member member = memberService.getMemberByNO(memberNo);
			if(member== null || member.getPermssion() == 2) {
				model.addAttribute("showMessage", "没有与查询相匹配的信息");

			}
			else{

				int depId =member.getDepartment();
				String departmentName =departmentService.getNameByID(depId);
				member.setDepartmentNa(departmentName);
				model.addAttribute("member", member);
			}

		}
		return "Chair/MemberManageShowOne";

	}
	
}
